from json import JSONDecodeError

from fastapi import Request, FastAPI
from fastapi.routing import APIRoute


class Route(APIRoute):
    """自定义路由"""

    def get_route_handler(self):
        original_route_handler = super().get_route_handler()

        async def log_request_detail(request: Request):
            logger = request.app.logger
            logger.info('start request'.center(60, '*'))
            logger.info(f'{request.method} {request.url}')
            try:
                white_url = 'upload'  # 上传文件路由会导致转json报错，原因待验证，先把上传图片直接跳过，不会影响业务
                if white_url in request.url.path:
                    pass
                else:
                    params = await request.json()
                    logger.info(params)
            except JSONDecodeError:
                pass
            logger.info('end request'.center(60, '*'))
            return await original_route_handler(request)

        return log_request_detail
